package com.chijun.mform.full;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * 加减乘除公式计算
 */
public class Calculator {
    // 运算符优先级判断
    private static int precedence(char operator) {
        if (operator == '+' || operator == '-') {
            return 1;
        } else if (operator == '*' || operator == '/') {
            return 2;
        }
        return 0;
    }

    // 中缀表达式转后缀表达式
    private static List<String> infixToPostfix(String infix) {
        List<String> postfix = new ArrayList<>();
        Stack<Character> operatorStack = new Stack<>();
        int i = 0;
        while (i < infix.length()) {
            char c = infix.charAt(i);
            if (Character.isDigit(c)) {
                StringBuilder num = new StringBuilder();
                while (i < infix.length() && (Character.isDigit(infix.charAt(i)) || infix.charAt(i) == '.')) {
                    num.append(infix.charAt(i));
                    i++;
                }
                postfix.add(num.toString());
            } else if (c == '(') {
                operatorStack.push(c);
                i++;
            } else if (c == ')') {
                while (!operatorStack.isEmpty() && operatorStack.peek()!= '(') {
                    postfix.add(operatorStack.pop().toString());
                }
                if (!operatorStack.isEmpty()) {
                    operatorStack.pop();
                }
                i++;
            } else {
                while (!operatorStack.isEmpty() && precedence(operatorStack.peek()) >= precedence(c)) {
                    postfix.add(operatorStack.pop().toString());
                }
                operatorStack.push(c);
                i++;
            }
        }
        while (!operatorStack.isEmpty()) {
            postfix.add(operatorStack.pop().toString());
        }
        return postfix;
    }

    // 计算后缀表达式
    private static BigDecimal calculatePostfix(List<String> postfix) {
        Stack<BigDecimal> operandStack = new Stack<>();
        for (String token : postfix) {
            if (Character.isDigit(token.charAt(0)) || token.contains(".")) {
                operandStack.push(new BigDecimal(token));
            } else {
                BigDecimal operand2 = operandStack.pop();
                BigDecimal operand1 = operandStack.pop();
                char operator = token.charAt(0);
                BigDecimal result;
                switch (operator) {
                    case '+':
                        result = operand1.add(operand2);
                        break;
                    case '-':
                        result = operand1.subtract(operand2) ;
                        break;
                    case '*':
                        result = operand1.multiply(operand2);
                        break;
                    case '/':
                        result = operand1.divide(operand2, 2, RoundingMode.HALF_UP);;
                        break;
                    default:
                        throw new IllegalArgumentException("非法运算符");
                }
                operandStack.push(result);
            }
        }
        return operandStack.pop();
    }

    public static BigDecimal evaluate(String infix) {
        List<String> postfix = infixToPostfix(infix);
        return calculatePostfix(postfix);
    }

















    // 判断是否是操作符
    private static boolean isOperator(char c) {
        return c == '+' || c == '-' || c == '*' || c == '/';
    }

    // 获取操作符的优先级
    private static int getPriority(char operator) {
        if (operator == '*' || operator == '/') {
            return 2;
        } else if (operator == '+' || operator == '-') {
            return 1;
        }
        return 0;
    }

    // 执行计算
    private static double calculate(double num1, double num2, char operator) {
        switch (operator) {
            case '+':
                return num1 + num2;
            case '-':
                return num1 - num2;
            case '*':
                return num1 * num2;
            case '/':
                return num1 / num2;
            default:
                return 0;
        }
    }

    public static double evaluate1(String expression) {
        Stack<Double> numberStack = new Stack<>();
        Stack<Character> operatorStack = new Stack<>();

        for (int i = 0; i < expression.length(); ) {
            char c = expression.charAt(i);
            if (Character.isDigit(c) || c == '.') {
                // 处理数字部分，可能是多位数字或者包含小数
                StringBuilder numBuilder = new StringBuilder();
                while (i < expression.length() && (Character.isDigit(expression.charAt(i)) || expression.charAt(i) == '.')) {
                    numBuilder.append(expression.charAt(i));
                    i++;
                }
                double num = Double.parseDouble(numBuilder.toString());
                numberStack.push(num);
            } else if (c == '(') {
                operatorStack.push(c);
                i++;
            } else if (c == ')') {
                while (operatorStack.peek() != '(') {
                    double num2 = numberStack.pop();
                    double num1 = numberStack.pop();
                    char op = operatorStack.pop();
                    numberStack.push(calculate(num1, num2, op));
                }
                operatorStack.pop(); // 弹出 '('
                i++;
            } else if (isOperator(c)) {
                while (!operatorStack.isEmpty() && getPriority(operatorStack.peek()) >= getPriority(c)) {
                    double num2 = numberStack.pop();
                    double num1 = numberStack.pop();
                    char op = operatorStack.pop();
                    numberStack.push(calculate(num1, num2, op));
                }
                operatorStack.push(c);
                i++;
            } else {
                i++;
            }
        }

        while (!operatorStack.isEmpty()) {
            double num2 = numberStack.pop();
            double num1 = numberStack.pop();
            char op = operatorStack.pop();
            numberStack.push(calculate(num1, num2, op));
        }

        return numberStack.pop();
    }
}
